// kit-watch 女儿老玩游戏，做个监视屏幕的服务.
package main

import (
	"bytes"
	"flag"
	"fmt"
	"image/jpeg"
	"net/http"
	"strings"

	"gitee.com/xuender/oils/logs"
	"github.com/kbinani/screenshot"
)

// nolint
var (
	cliPass  string
	cliDebug bool
)

// 屏幕截图.
func display(num int) ([]byte, error) {
	bounds := screenshot.GetDisplayBounds(num)

	img, err := screenshot.CaptureRect(bounds)
	if err != nil {
		return nil, err
	}

	buf := new(bytes.Buffer)
	quality := 50

	if err := jpeg.Encode(buf, img, &jpeg.Options{Quality: quality}); err != nil {
		return nil, err
	}

	return buf.Bytes(), nil
}

// 监听.
func watch(writer http.ResponseWriter, req *http.Request) {
	if cliPass != "" && !strings.Contains(req.URL.Path, cliPass) {
		fmt.Fprintf(writer, "401")

		return
	}

	if cliDebug {
		logs.Debug("爸爸来了")
	}

	if strings.HasSuffix(req.URL.Path, "num") {
		n := screenshot.NumActiveDisplays()
		fmt.Fprintf(writer, "显示器数量: %d", n)

		return
	}

	num := 0

	if strings.HasSuffix(req.URL.Path, "1") {
		num = 1
	}

	data, err := display(num)
	if err != nil {
		fmt.Fprint(writer, err.Error())
	}

	writer.Header().Set("Content-Type", "image/jpeg")
	_, _ = writer.Write(data)
}

func main() {
	cliPort := 9090
	// 加载命令行
	flag.StringVar(&cliPass, "a", "", "Access password.")
	flag.IntVar(&cliPort, "p", cliPort, "Http port number.")
	flag.BoolVar(&cliDebug, "d", false, "Debug mode.")
	flag.Parse()
	http.HandleFunc("/", watch)
	logs.Panic(http.ListenAndServe(fmt.Sprintf(":%d", cliPort), nil))
}
